package com.demo.component.base;

import com.demo.component.base.model.communication.RequestResult;
import com.demo.component.base.model.communication.RequestResultData;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

public class BaseController {
    protected <T extends RequestResult> ResponseEntity<Object> processRestRequestResult(RequestResult result) {
        if (!result.isSuccess()) {
            return processErrorCode(result);
        }

        return ResponseEntity.status(HttpStatus.OK).body(result.getMessage());
    }

    protected <T extends RequestResult> ResponseEntity<Object> processRestRequestResultWithData(RequestResultData<?> resultData) {
        if (!resultData.isSuccess()) {
            return processErrorCode(resultData);
        }

        return ResponseEntity.status(HttpStatus.OK).body(resultData.getResultData());
    }

    protected ResponseEntity<Object> processErrorCode(RequestResult result) {
        String errorMessage = result.getMessage();
        try {
            String errorCode = result.getInternalStatus();
            if (errorCode == null) {
                errorCode = HttpStatus.INTERNAL_SERVER_ERROR.toString();
            }

            try {
                int errorCodeNum = Integer.parseInt(errorCode);
                HttpStatus httpStatus = HttpStatus.valueOf(errorCodeNum);

                return ResponseEntity.status(httpStatus).body(errorMessage);
            } catch (IllegalArgumentException e) {
                // Handle the case where errorCode is not a valid HTTP status code
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage);
            }
        } catch (NumberFormatException ex) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorMessage);
        }
    }
}
